﻿#region --- New BSD License ---
/*
Copyright (c) 2009, Timko Technologies, L.L.C. (http://www.timkotech.com)
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this 
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation 
and/or other materials provided with the distribution.

* Neither the name of Timko Technologies, L.L.C. nor the names of its contributors 
may be used to endorse or promote products derived from this software without 
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*/
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;

namespace InstantIRC
{
    public partial class MainForm : Form
    {
        private IAsyncResult _ar = null;
        private TcpClient _client = null;
        private NetworkStream _stream = null;
        private IRCUser _user = null;

        #region --- Static Data (differ per build) ---
        /* Modify these settings for the initial IRC
         * connection.  The Nick Control Box will give
         * the user to the ability to change the Nick
         * and the ability to change all of the other
         * data. More-or-less, this is just to nudge a
         * new user into the right direction up the start
         * of this application */
        private static string nick = "UserNick";  // Nickname
        private static string name = "UserNick_";  // User's name
        private static string host = "MahPuter";  // User's host
        private static string servername = "exmaple.com"; // User's system name
        private static string realname = "Joe Blowski"; // User's real name
        private static string nickservPass = ""; // User's nickServ Password
        private static string chan = "#main"; // Channel for User to Join [requires leading #]
        private static string hostname = "irc.freenode.net"; // IRC Server
        private static int port = 6667; // IRC Port
        

        #endregion

        private delegate void ThreadCallback(string s);

        public MainForm()
        {
            InitializeComponent();

            _user = new IRCUser(nick, name, host, servername, realname, nickservPass);
        }

        ~MainForm()
        {
            if (_client != null && _client.Connected)
                _client.EndConnect(_ar);
        }

        private void _bConnect_Click(object sender, EventArgs e)
        {
            _client = new TcpClient();
            _ar = _client.BeginConnect(hostname, port, new AsyncCallback(TcpCallback), this);

            while (_stream == null) ;
            byte[] nick, user, nickserv, channel;
            nick = StringToByte(_user.ToNickString());
            user = StringToByte(_user.ToUserString());
            nickserv = StringToByte(_user.ToNickServString());
            channel = StringToByte("JOIN " + chan);

            _stream.Write(nick, 0, nick.Length);
            _stream.Write(user, 0, user.Length);

            // Tried waiting for stream connection and such, later this will
            // need to become a wait for the specific server reply and then
            // we can send that in as well.
            Thread.Sleep(1500); // Give it enough time to connect.
            _stream.Write(nickserv, 0, nickserv.Length);
            _stream.Write(channel, 0, channel.Length);
        }

        private byte[] StringToByte(string s)
        {
            byte[] b = new byte[s.Length + 1];
            int i = 0;
            foreach (char c in s)
            {
                b[i++] = (byte)c;
            }
            b[i] = (byte)'\n';
            return b;
        }

        private void _InputBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && _InputBox.Text != string.Empty)
            {
                string text = _InputBox.Text;
                int loc = text.IndexOf("\r\n");
                if (loc < text.Length - 1 && loc != -1)
                    text = text.Substring(loc + 2);
                byte[] b = StringToByte(string.Format(":{0} PRIVMSG {1} :{2}", nick, chan, text));
                if (!_client.Connected)
                {
                    MessageBox.Show("Not Connected to server");
                    return;
                }
                _OutputBox.AppendText(string.Format("\n[{0}] {1}> {2}", chan, nick, text));
                _stream.Write(b, 0, b.Length);

                _InputBox.Text = string.Empty;

                e.Handled = true;
            }

            e.Handled = false;
        }

        private void WriteStream(string s)
        {
            string output = s;

            IRCResponse resp = new IRCResponse(s);
            if (resp.IsValid)
            {
                switch (resp.Command)
                {
                    case IRCCmd.PRIVMSG:
                        output = string.Format("\n[{0}] {1}> {2}", resp.Target, resp.Nick, resp.Message);
                        break;
                    case IRCCmd.KICK:
                        output = string.Format("\n{{0} was kicked by {1} >> {2} }", resp.SubTarget, resp.Nick, resp.Message);
                        break;
                    case IRCCmd.PING:
                        // PING|PONGS shouldn't output unless user changes settings
                        byte[] b = StringToByte(string.Format("\nPONG {0}", resp.Message));
                        _stream.Write(b, 0, b.Length);
                        output = string.Empty;
                        break;
                    case IRCCmd.JOIN:
                    case IRCCmd.QUIT:
                    case IRCCmd.PART:
                        // This will be needed to be controlled by the settings.
                        output = string.Empty;
                        break;
                    default:
                        if (resp.Code != 0)
                        {
                            switch (resp.Code)
                            {
                                case 353:
                                    LoadUsers(resp.Message);
                                    break;
                                default:
                                    output = s;
                                    break;
                            }
                        }
                        else
                        {
                            output = s;
                        }
                        break;
                }
            }

            _OutputBox.AppendText(output);
        }

        private void LoadUsers(string p)
        {
            string[] users = p.Split(' ');
            foreach (string u in users)
            {
                _lvUsers.Items.Add(new ListViewItem(u));
            }
        }

        private static void TcpCallback(IAsyncResult ar)
        {
            MainForm ins = (MainForm)ar.AsyncState;
            ins._stream = ins._client.GetStream();

            int j;
            string output = string.Empty;
            while ((j = ins._stream.ReadByte()) != -1)
            {
                if (j == '\r')
                {
                    ins.Invoke(new ThreadCallback(ins.WriteStream), output);
                    output = string.Empty;
                }
                else
                {
                    output += ((char)j).ToString();
                }
            }
        }

        private void _OutputBox_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.LinkText);
        }

        private void _bAbout_Click(object sender, EventArgs e)
        {
            About a = new About();
            a.Show();
        }
    }
}
